<template>
  <!-- 数据加载 -->
  <el-container>
      <el-main class="vs-workbench-main-scoped">
        <el-card shadow="never" class="vs-workbench-card-scoped" v-loading="isUploading"
                 element-loading-text="loading"
                 element-loading-spinner="el-icon-loading"
                 element-loading-background="rgba(0, 0, 0, 0.8)">
          <el-row :gutter="20">
            <el-col :span="5" style="height: calc(100vh - 235px);overflow-y: auto;">
              <div class="block">
                <p @click="queryAllData" style="cursor: pointer;">本地文件类型：</p>
                <el-tree
                    class="leftTree"
                    :data="fileTypeList"
                    node-key="id"
                    :highlight-current="true"
                    @node-click="handlerNode"
                    default-expand-all>
                  <div class="custom-tree-node" slot-scope="{ node, data }">
                    <div>{{ data.name }}</div>
                  </div>
                </el-tree>
              </div>
            </el-col>
            <el-col :span="19" v-if="fileType.code != 'DATALOAD_LAS'">
              <el-row>
                <el-form
                    :inline="true"
                    class="demo-form-inline"
                >
                  <el-form-item>
                    <el-button
                      type="info"
                      plain
                      icon="el-icon-upload2"
                      size="mini"
                      @click="handleImport"
                      v-hasPermi="['system:user:import']"
                      :disabled="!fileType.code"
                    >导入</el-button>
                  </el-form-item>
                  <el-form-item>
                    <el-button size="medium" @click="loadData" :disabled="true">数据库加载+</el-button>
                    <!--<el-button size="medium" @click="loadData" :disabled="!project.oidField">数据库加载+</el-button>-->
                  </el-form-item>
                  <el-form-item>
                    <el-button size="medium" :disabled="!fileType.code" @click="downLoadFile">模板下载</el-button>
                  </el-form-item>
                  <el-form-item>
                    <el-button size="medium" :disabled="!fileType.code" @click="openHistoryDialog()">查看历史</el-button>
                  </el-form-item>
                  <el-form-item style="float: right;">
                    <el-input placeholder="请输入文件名称" v-model="name" class="input-with-select">
                      <el-button slot="append" icon="el-icon-search" @click="querySearch"></el-button>
                    </el-input>
                  </el-form-item>
                </el-form>
              </el-row>
              <el-row>
                <el-table
                    ref="multipleTable"
                    :data="tableData"
                    tooltip-effect="dark"
                    height="calc(100vh - 310px)"
                    :style="tableStyle"
                    fit
                    border
                    stripe
                    key="csv"
                >
                  <el-table-column
                      type="index"
                      :index="indexMethod"
                      label="序号"
                      align="center"
                      width="50"
                  ></el-table-column>
                  <el-table-column
                      prop="parentName"
                      label="分类"
                      show-overflow-tooltip
                      header-align="center"
                      align="center"
                      min-width="100"
                  >
                  </el-table-column>
                  <el-table-column
                      prop="typeName"
                      label="数据类型"
                      show-overflow-tooltip
                      header-align="center"
                      align="center"
                      min-width="180"
                  >
                  </el-table-column>
                  <el-table-column
                      prop="fileSource"
                      label="文件数据源"
                      header-align="center"
                      align="center"
                      min-width="80"
                  >
                  </el-table-column>
                  <el-table-column
                      prop="fileName"
                      label="文件名称"
                      show-overflow-tooltip
                      header-align="center"
                      align="center"
                      min-width="180"
                  >
                  </el-table-column>
                  <el-table-column
                      prop="fileSize"
                      label="文件大小"
                      min-width="100"
                      header-align="center"
                      align="center"
                  >
                    <template slot-scope="scope">
                      {{ scope.row.fileSize + 'B' }}
                    </template>
                  </el-table-column>
                  <el-table-column
                      prop="operationTime"
                      label="上传时间"
                      min-width="150"
                      header-align="center"
                      align="center"
                  >
                  </el-table-column>
                  <el-table-column
                      prop="operatorName"
                      label="操作者"
                      min-width="80"
                      header-align="center"
                      align="center"
                  >
                  </el-table-column>
                  <el-table-column
                      prop="state"
                      label="状态"
                      min-width="100"
                      header-align="center"
                      align="center"
                  >
                    <template slot-scope="scope">
                      <!--0待配置 1待加载 2加载成功 3 加载失败-->
                      <template v-if="scope.row.state == '0'">
                        <el-tag type="warning">待配置</el-tag>
                      </template>
                      <template v-if="scope.row.state == '1'">
                        <el-tag type="warning">待加载</el-tag>
                      </template>
                      <template v-if="scope.row.state == '3'">
                        <el-tag type="danger">加载失败</el-tag>
                      </template>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center" min-width="180">
                    <template slot-scope="scope">
                      <el-button type="text" size="small" @click="setTitleInfo(scope.row)">设置</el-button>
                      <el-button type="text" size="small" :disabled="scope.row.state == '0'"
                                 @click="loadFileData(scope.row)">加载
                      </el-button>
                      <el-button type="text" size="small" v-if="scope.row.state == '3'"
                                 @click="showError(scope.row)">错误详情
                      </el-button>
                      <el-button type="text" size="small" @click="deleteRow(scope.row)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-row>
              <el-row>
                <!--分页-->
                <div class="pagination" @click="pageClick($event)">
                  <el-pagination
                      @size-change="handleSizeChange"
                      @current-change="handleCurrentChange"
                      :current-page="currentPage"
                      :page-sizes="[10, 20, 30, 40]"
                      :page-size="pageSize"
                      layout="sizes,total,prev,pager,next"
                      :total="total"
                  ></el-pagination>
                </div>
              </el-row>
            </el-col>
            <el-col :span="19" v-if="fileType.code === 'DATALOAD_LAS'">
              <div>
                <input type="file" id="uploadDirectory" :accept="'.las'" webkitdirectory style="display:none"
                       @change="bindUpdateHandle">
              </div>
              <el-row>
                <el-form :inline="true" class="demo-form-inline">
                  <el-form-item>
                    <el-upload class="upload-input" ref="uploadLas" action="" :show-file-list="false" multiple
                               accept=".las" :auto-upload="false" :on-change="lasFileChange">
                      <el-button size="medium" slot="trigger">选择文件</el-button>
                      <el-button v-if='!isIE' size="medium" style="margin-left:10px" @click="filesDirectoryEvent">
                        本地文件夹
                      </el-button>
                    </el-upload>
                  </el-form-item>
                  <el-form-item>
                    <el-button size="medium" :disabled="!fileType.code" @click="openHistoryDialog()">查看加载历史</el-button>
                  </el-form-item>
                  <el-form-item>
                    <el-button size="medium" :disabled="!fileType.code" @click="bulkLoading()">批量加载</el-button>
                  </el-form-item>
                  <el-form-item style="float: right;">
                    <el-input placeholder="请输入文件名称" v-model="name" class="input-with-select">
                      <el-button slot="append" icon="el-icon-search" @click="querySearch"></el-button>
                    </el-input>
                  </el-form-item>
                </el-form>
              </el-row>
              <el-row>
                <el-table ref="las" tooltip-effect="dark" height="calc(100vh - 310px)" fit border
                          stripe :data="lasTableData" @selection-change="uploadFileSelection" key="las">
                  <el-table-column type="selection" min-width="60"></el-table-column>
                  <el-table-column align="center" type="index" label="序号" min-width="60"></el-table-column>
                  <el-table-column header-align="center" align="center" min-width="150" prop="fileName"
                                   label="文件名称"></el-table-column>
                  <el-table-column align="center" prop="fileHead" label="文件井号" min-width="100"></el-table-column>
                  <el-table-column header-align="center" align="center" prop="fileDataType" min-width="100"
                                   label="文件类型"></el-table-column>
                  <el-table-column header-align="center" min-width="100" align="center" prop="fileSize" label="文件大小">
                    <template slot-scope="scope">
                      <span>{{ getFileSize(scope.row.fileSize) }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column header-align="center" min-width="100" align="center" prop="PREFIX" label="数据标记">
                    <template slot-scope="scope">
                      <span>{{ scope.row.prefix ? scope.row.prefix : '原始数据' }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="数据库对应井号" min-width="200">
                    <template slot-scope="scope">
                      <el-tag v-if="scope.row.wellLabel" class="wellStatus" type="success">{{
                          scope.row.wellLabel
                        }}
                      </el-tag>
                      <el-tag v-else type="warning" class="wellStatus">{{ scope.row.checkStatus }}</el-tag>
                      <el-button :disabled="scope.row.checkStatus == '加载中'" type="primary"
                                 class="selectWellButton" size="mini"
                                 @click="chooseWell(scope.row,scope.$index)">选择井号
                      </el-button>
                    </template>
                  </el-table-column>
                  <el-table-column header-align="center" align="center" prop="createTime" label="上传时间"
                                   min-width="150"></el-table-column>
                  <el-table-column header-align="center" align="center" prop="creater" label="操作者"
                                   min-width="100"></el-table-column>
                  <el-table-column align="center" label="状态" min-width="120">
                    <template slot-scope="scope">
                      <el-tag v-if="scope.row.status == 0">未加载</el-tag>
                      <el-tag v-if="scope.row.status == 1" type="success">加载中</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="操作" min-width="150">
                    <template slot-scope="scope">
<!--                      <el-button @click="upLoadFile(scope.row,scope.$index)" type="text" size="small"-->
<!--                                 :disabled="scope.row.wellLabel == undefined || scope.row.wellLabelId == '' || scope.row.checkStatus == '加载中' ">-->
<!--                        加载-->
<!--                      </el-button>-->
                      <el-button :disabled="scope.row.checkStatus == '加载中'" @click="deleteClick(scope.row,scope.$index)"
                                 type="text" size="small">删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-row>
              <el-row>
                <!--分页-->
                <div class="pagination" @click="pageClick($event)">
                  <el-pagination
                      @size-change="handleSizeChange"
                      @current-change="handleCurrentChange"
                      :current-page="currentPage"
                      :page-sizes="[10, 20, 30, 40]"
                      :page-size="pageSize"
                      layout="sizes,total,prev,pager,next"
                      :total="total"
                  ></el-pagination>
                </div>
              </el-row>
            </el-col>
          </el-row>
        </el-card>
        <el-dialog :visible="dialogTableVisible"
                   class="historyDialog"
                   top="15vh"
                   :title="dialogTitle"
                   width="1000px"
                   @close="dialogCancel"
                   :close-on-click-modal="false">
          <div class="table" style="height: 630px;overflow: auto;">
            <el-row>
              <div>
                <span style="color:red;">&emsp;	&emsp;&emsp;*&ensp;以下字段必须设置：</span>
                <span style="font-size: 15px">{{ mustCode }}</span>
              </div>
            </el-row>
            <el-row style="margin-top: 5px">
              <el-table
                  ref="multipleTable"
                  style="width: 100%;height:100%;"
                  max-height="600"
                  :data="fileSetInfo"
                  tooltip-effect="dark"
                  border
                  stripe
              >
                <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>
                <el-table-column align="center" property="fileTitle" label="文件字段"></el-table-column>
                <el-table-column align="center" label="表字段">
                  <template slot-scope="scope">
                    <el-select v-model="scope.row.tableCode" filterable placeholder="请选择" clearable
                               @change="tableFilesChange(scope.row,scope.$index)">
                      <el-option
                          v-for="item in tableConfig"
                          :key="item.value"
                          :label="item.key"
                          :value="item.value"
                      ></el-option>
                    </el-select>
                  </template>
                </el-table-column>
              </el-table>
            </el-row>
          </div>
          <div slot="footer" style="margin-top: 10px;text-align: center;">
            <el-button size="medium" type="primary" @click="dialogConfirm" style="margin-right: 20px;">确定</el-button>
            <el-button size="medium" type="primary" @click="dialogCancel">取消</el-button>
          </div>
        </el-dialog>
        <el-dialog :visible="dialogHistoryVisible"
                   class="historyDialog"
                   top="15vh"
                   title="加载历史"
                   width="1200px"
                   @close="closeHistoryDialog"
                   :close-on-click-modal="false">
          <div class="table" style="height: 520px;overflow: auto;margin-top: 10px">
            <el-row>
              <el-table
                  v-if="fileType.code != 'DATALOAD_LAS'"
                  ref="multipleHistoryTable"
                  style="width: 100%;height:100%;"
                  height="calc(100vh - 505px)"
                  :data="tableHistoryData"
                  tooltip-effect="dark"
                  border
                  stripe
              >
                <el-table-column type="index" :index="indexHistoryMethod" label="序号" align="center"
                                 width="50"></el-table-column>
                <el-table-column prop="parentName" label="分类" header-align="center" align="center"
                                 min-width="100"></el-table-column>
                <el-table-column prop="typeName" label="数据类型" header-align="center" align="center"
                                 min-width="150"></el-table-column>
                <el-table-column prop="fileSource" label="文件数据源" header-align="center" align="center"
                                 min-width="100"></el-table-column>
                <el-table-column prop="fileName" label="文件名称" header-align="center" align="center" min-width="200">
                </el-table-column>
                <el-table-column prop="fileSize" label="文件大小" min-width="100" header-align="center" align="center">
                  <template slot-scope="scope">
                    <span>{{ getFileSize(scope.row.fileSize) }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="operationTime" label="上传时间" min-width="150" header-align="center" align="center">
                </el-table-column>
                <el-table-column prop="operatorName" label="操作者" min-width="80" header-align="center" align="center">
                </el-table-column>
                <el-table-column prop="state" label="状态" min-width="100" header-align="center" align="center">
                  <template slot-scope="scope">
                    <!--0待配置 1待加载 2加载成功 3 加载失败-->
                    <template v-if="scope.row.state == '2'">
                      <el-tag type="success">加载成功</el-tag>
                    </template>
                  </template>
                </el-table-column>
              </el-table>
              <el-table
                  v-if="fileType.code == 'DATALOAD_LAS'"
                  ref="multipleHistoryTable"
                  style="width: 100%;height:100%;"
                  height="calc(100vh - 505px)"
                  :data="tableHistoryData"
                  tooltip-effect="dark"
                  border
                  stripe
              >
                <el-table-column type="expand" align="right" min-width="35" label-class-name="details-icon-column">
                  <template slot-scope="props">
                    <el-form label-position="left">
                      <el-form-item label="加载详情">
                        <span style="white-space:normal;">{{ props.row.loadInfo }}</span>
                      </el-form-item>
                    </el-form>
                  </template>
                </el-table-column>
                <el-table-column type="index" :index="indexHistoryMethod" label="序号" align="center"
                                 min-width="40"></el-table-column>
                <el-table-column align="center" prop="fileName" label="文件名" min-width="50"></el-table-column>
                <el-table-column align="center" prop="fileType" label="类型" min-width="40"></el-table-column>
                <el-table-column header-align="center" align="center" prop="fileDataType" min-width="40"
                                 label="文件数据类型"></el-table-column>
                <el-table-column header-align="center" align="center" prop="fileSize" label="文件大小(M)" min-width="50">
                  <template slot-scope="scope">
                    <span>{{ getFileSize(scope.row.fileSize) }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="状态" min-width="80">
                  <template slot-scope="scope">
                    <!-- scope.row.status -->
                    <el-tag v-if="scope.row.status == 0">未加载</el-tag>
                    <el-tag v-if="scope.row.status == 1" type="success">加载中</el-tag>
                    <el-tag v-if="scope.row.status == 2" type="danger">加载失败</el-tag>
                    <el-tag v-if="scope.row.status == 3" type="success">加载成功</el-tag>
                  </template>
                </el-table-column>
                <el-table-column align="center" prop="creater" label="创建人" min-width="80"></el-table-column>
                <el-table-column align="center" prop="createTime" label="创建时间" min-width="100"></el-table-column>
              </el-table>
            </el-row>
            <el-row>
              <!--分页-->
              <div class="pagination" @click="pageClick($event)" style="margin-top: 10px">
                <el-pagination
                    @size-change="handleSizeHistoryChange"
                    @current-change="handleCurrentHistoryChange"
                    :current-page="currentHistoryPage"
                    :page-sizes="[10, 20, 30, 40]"
                    :page-size="pageHistorySize"
                    layout="sizes,total,prev,pager,next"
                    :total="totalHistory"
                ></el-pagination>
              </div>
            </el-row>
          </div>
        </el-dialog>
        <el-dialog class="dialogForForm wisWellDialog" title="选择对应井号" :visible.sync="wellSelectObj.dialogWellVisible">
          <el-divider class="topLine"></el-divider>
          <el-form label-width="120px">
            <el-form-item label="原文件名称:">{{ wellSelectObj.row.fileName }}</el-form-item>
            <el-form-item label="选择对应井号:">
              <el-select v-model="wellSelectObj.wellLabelId" filterable placeholder="请选择">
                <el-option
                    v-for="item in lasModelList"
                    :key="item.key"
                    :label="item.label"
                    :value="item.key"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <el-divider class="bottomLine"></el-divider>
          <div style="margin-top:10px;text-align:center;">
            <el-button type="primary" @click="selectWellConfirm">确定</el-button>
            <el-button @click="selectWellCancel">取消</el-button>
          </div>
        </el-dialog>
        <!-- 导入对话框 -->
        <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
          <el-upload
            ref="upload"
            :limit="1"
            accept=".csv"
            :headers="upload.headers"
            :action="upload.url"
            :disabled="upload.isUploading"
            :before-upload="checkFileExist"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="false"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip text-center" slot="tip">
              <span>仅允许导入csv格式文件。</span>
            </div>
          </el-upload>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitFileForm">确 定</el-button>
            <el-button @click="upload.open = false">取 消</el-button>
          </div>
        </el-dialog>
      </el-main>
  </el-container>
</template>
<script>

import cascaderTree from "@/lib/cascaderTree";
import {Loading} from "element-ui";
import {uuid} from "@/lib/utils";
import {getFileType,getRecordList,getSetInfo,loadTableData,deleteData,uploadingFile,updateInfo,downloadTemplate} from "@/api/datamanage/dataLoading";
import {getToken} from "@/utils/auth";

export default {
  //名称
  name: "dataLoading",
  components: {},
  data() {
    return {
      //项目信息
      // project: JSON.parse(sessionStorage.getItem("selectProject")) || {},
      project:{
          "projectId": "A1A7551BD8564F7E97329C5B6AC853A9",
          "projectName": "分公司培训测试项目2022.6",
          "stepId": "28901E61E78A48258BB04C4B11BA66F1",
          "projectBasin": "盆地1",
          "projectBasinName": null,
          "projectStructure": "构造单元1",
          "projectStructureName": "构造单元1",
          "oidField": "油气田1",
          "oidFieldTm": "field1",
          "oidFieldName": "油气田1",
          "stepName": "开发评估",
          "nodeEvaluateTime": "2022/06/07",
          "nodeList": [
              {
                  "id": "DEVE_ASSESSMENT",
                  "name": "开发评估"
              }
          ]
      },
      fileType: {
        id: "",
        pid: "",
        name: "",
        code: "",
        filePath: "",
        floorCode: ""
      },
      wellSelectObj: { //wis文件选择对应井号弹窗
        dialogWellVisible: false,
        wellLabelId: '',
        wellLabel: '',
        prefix: '',
        index: 0,
        row: {}
      },
      // 当前页码
      currentPage: 1,
      // 每页的数据条数
      pageSize: 10,
      total: 0,
      //防止重复匹配模板
      matching: 0,
      // 当前页码
      currentHistoryPage: 1,
      // 每页的数据条数
      pageHistorySize: 10,
      //历史数据总数
      totalHistory: 0,
      //上传文件数量限制
      uploadLimit: 50,
      tableStyle: "width:100%;height:calc(100vh - 310px);",
      fileList: [],
      fileTypeList: [],
      //表数据
      tableData: [],
      //las表数据
      lasTableData: [],
      //历史表格数据
      tableHistoryData: [],
      lasModelList: [],
      //设置表数据
      fileSetInfo: [],
      //设置选择框设置
      tableConfig: [],
      //选中的类型
      matchedList: [],
      //选中数据
      loadingList: [],
      name: "",
      //弹窗标题
      dialogTitle: "",
      //提示选项
      mustCode: "",
      form: {},
      //选中行
      selectRow: {},
      //选择的节点
      chooseNode: {},
      //文件对象
      upFilesObj: {},
      // 是否为IE浏览器
      isIE: false,
      //是否上传
      isUploading: false,
      //设置弹窗
      dialogTableVisible: false,
      //查看历史
      dialogHistoryVisible: false,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: ""
      },
    };
  },
  created() {
    this.getFileTypeQuery();
    this.querySearch();
  },
  mounted() {
    //文件夹上传事件绑定
    // this.directory();
    //检测是否为IE浏览器
    if (!!window.ActiveXObject || "ActiveXObject" in window) {
      this.isIE = true
    } else {
      this.isIE = false
    }
  },
  methods: {
    /**
     * 序号
     */
    indexMethod(index) {
      return index + this.pageSize * (this.currentPage - 1) + 1;
    },
    /**
     * 序号
     */
    indexHistoryMethod(index) {
      return index + this.pageHistorySize * (this.currentHistoryPage - 1) + 1;
    },
    /**
     * 设置弹窗
     */
    setTitleInfo(row, index) {
      // debugger;
      this.dialogTitle = "设置" + row.typeName
      this.selectRow = row
      this.querySetData(row).then(resp => {
        this.mustCode = resp.mustCode
        this.matchedList = resp.matchedList
        this.fileSetInfo = resp.fileSetInfo
        this.tableConfig = resp.tableConfig
        this.dialogTableVisible = true;
      })
    },
    /**
     * 设置弹窗确认
     */
    dialogConfirm() {
      let param = {
        fileSetInfo: this.fileSetInfo,
        record: this.selectRow,
        code: this.fileType.code
      }
      updateInfo(param).then((data) => {
          console.log(data);
          //if(data.code == 200){
            this.dialogTableVisible = false;
            this.queryTableData()
          /*}else{
            this.dialogTableVisible = false;
            this.$message.warning("配置字段保存错误!")
          }*/
      }).catch(e=>{
        this.dialogTableVisible = false;
        this.$message.warning("配置字段保存错误!")
      });


      // axios({
      //   method: "post",
      //   url: AJAXPathConfig.dataManage.getBasePath() + '/dataLoad/update/info',
      //   data: param,
      //   success: data => {
      //     this.dialogTableVisible = false;
      //     this.queryTableData()
      //   },
      //   error: e => {
      //     this.dialogTableVisible = false;
      //     this.$message.warning("配置字段保存错误!")
      //   }
      // });
    },
    /**
     * 设置弹窗取消
     */
    dialogCancel() {
      this.dialogTableVisible = false;
    },
    /**
     *表字段切换
     */
    tableFilesChange(row, index) {
      if (this.matchedList.indexOf(row.tableCode) !== -1) {
        this.$message.warning("重复选择字段,请重新选择")
        row.tableCode = ''
      }
      this.fileSetInfo.splice(index, 1, row)
      this.matchedList = this.fileSetInfo.map(item => {
        if (item.tableCode != null && item.tableCode != undefined && item.tableCode != "")
          return item.tableCode
      })
    },

    /**
     * 查询设置弹窗数据
     */
    querySetData(row) {
      return new Promise((resolve, reject) => {
        let param = {
          code: this.fileType.code,
          id: row.id
        }
        getSetInfo(param).then((data) =>{
            //if(data.code == 200){
              resolve(data);
            //}
        });
      })
    },

    /**
     * 加载文件
     */
    loadFileData(row) {
      let loading = Loading.service({
        fullscreen: true,
        text: "数据加载中，请稍后",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      let fileData = new FormData();
      fileData.append("id", row.id);
      fileData.append("projectId", row.projectId);
      fileData.append("stepId", row.stepId);
      fileData.append("nodeId", row.nodeId);
      fileData.append("typeCode", this.fileType.code);
      fileData.append("userCode", row.operator);

      loadTableData(fileData).then((data) => {
        console.log("加载")
        console.log(data)
          if(data.state == 'success'){
            this.$message.success("文件加载成功")
          }else{
            this.$message.warning("文件加载失败")
          }
          this.queryTableData();
          loading.close()
      })
    },
    /*查看错误信息*/
    showError(row) {
      this.$confirm(row.errorText, "提示", {
        showCancelButton: false,
        showConfirmButton: false,
        type: "warning"
      }).then(() => {
      }).catch(() => {
      });
    },
    /**
     * 删除行
     */
    deleteRow(row) {
      this.$confirm("是否删除当前数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let params = {
            id: row.id,
        }
        deleteData(params).then((data) => {
            if(data.code == 200){
              this.$message.success("删除成功")
              this.queryTableData();
            } else {
              this.$message({
                message: "删除失败",
                type: "warning"
              });
            }
        })

      }).catch(() => {
      });
    },
    /**
     * 查询
     */
    queryAllData() {
      this.currentPage = 1;
      this.fileType = {};
      this.querySearch();
    },
    /**
     * 下载文件
     */
    downLoadFile() {
      let params = {
        name:this.fileType.name + '.csv',
        path:this.fileType.filePath
      }
      ////window.open(downloadTemplate(params), '_blank');
      this.download('/assessDataMessage/dataManage/dataLoad/downloadTemplate',
        params
        , this.fileType.name+ '.csv');
    },
    /*从数据库中加载数据*/
    loadData(){
      const loading = Loading.service({
        lock: true, //lock的修改符--默认是false
        text: "正在提取成果中", //显示在加载图标下方的加载文案
        spinner: "el-icon-loading", //自定义加载图标类名
        background: "rgba(0, 0, 0, 0.7)", //遮罩层颜色
        target: document.querySelector("#table"), //loadin覆盖的dom元素节点
      });
      axios({
        method: "post",
        url: AJAXPathConfig.dataManage.getBasePath() + "/dataLake/save",
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        data: {
          "blockId": "",
          "nodeId": this.project.nodeList.map(n=>n.id).join(","),
          "ogfId": this.project.oidField,
          //"operator": this.userInfo.loginName,
          "projectId": this.project.projectId,
          "stepId": this.project.stepId
        },
        success: (data) => {
          if (!data.meta.success || data === "") {
            this.$message({
              type: "warning",
              message: "拉取数据失败！",
            });
            return;
          } else {
            this.$message({
              type: "success",
              message: "拉取数据完成！",
            });
          }
        },
        error: (e) => {
          this.$message({
            type: "warning",
            message: "拉取数据失败！",
          });
        },
      }).finally(()=>{
        loading.close();
      });
    },
    /**
     * 获取全部文件类型
     */
    getFileTypeQuery() {
      let params = {};
      getFileType(params).then((data) => {
          if (!data.code == 200) {
            this.$message({
              message: '查询文件分类失败！',
              type: "warning"
            });
            return;
          } else {
            this.fileTypeList = new cascaderTree(data, "id", "pid").init();
            this.handlerNode(this.fileTypeList[0].children[0])
          }
      });

    },
    /**
     * 点击树节点
     */
    handlerNode(data) {
      this.fileType = data;
      //重置分页
      this.pageSize = 10
      this.total = 0
      this.currentPage = 1;
      this.name = '';
      this.queryTableData();
    },
    /**
     * 获取数据
     */
    queryTableData() {
      if (this.fileType.code == 'DATALOAD_LAS') {
        this.$message.warning("LAS文件功能尚在开发中");
      } else {
        let params = {
            code: this.fileType.id || '',
            projectId: this.project.projectId,
            name: this.name,
            status: "query",
            pageNum: this.currentPage,
            pageSize: this.pageSize
        };
        getRecordList(params).then((data) => {
            if (!data.code == 200) {
              this.$message({
                message: "数据列表查询失败！",
                type: "warning"
              });
              return;
            } else {
              this.tableData = data.rows;
              this.total = data.total;
            }
        });
      }
    },
    /**
     * 查看历史
     */
    queryHistory() {
      return new Promise((resolve, reject) => {
        let param = {
          code: this.fileType.id || '',
          projectId: this.project.projectId,
          name: "",
          status: "history",
          pageNum: this.currentHistoryPage,
          pageSize: this.pageHistorySize
        }
        if (this.fileType.code == 'DATALOAD_LAS') {
          this.$message.warning("暂无LAS文件历史")
        } else {
          getRecordList(param).then((data) =>{
              if (!data.code == 200) {
                reject()
              } else {
                resolve(data)
              }
          })

        }
      })
    },
    /**
     * 选择井号弹窗下拉切换事件
     */
    chooseWell(row, index) {
      this.wellSelectObj.wellLabelId = row.wellLabelId || '';
      this.wellSelectObj.wellLabel = row.wellLabel || '';
      this.wellSelectObj.index = index;
      this.wellSelectObj.row = {...row};
      this.wellSelectObj.dialogWellVisible = true;
    },
    /**
     * las文件选择井号后确定
     */
    selectWellConfirm() {
      if (!this.wellSelectObj.wellLabelId) {
        this.$message({
          type: "warning",
          message: '请选择井号！'
        })
        return
      }
      const row = Object.assign({...this.wellSelectObj.row}, {
        wellLabelId: this.wellSelectObj.wellLabelId,
        wellLabel: this.lasModelList.find(item => item.key == this.wellSelectObj.wellLabelId).value
      })
      this.matchingSingleLasTemplate(row, this.wellSelectObj.index)
      this.wellSelectObj.dialogWellVisible = false
    },
    /**
     *单个las文件匹配
     */
    matchingSingleLasTemplate(row, index) {
      if (row.wellLabel && row.wellLabelId) {
        this.lasTableData.splice(index, 1, row)
        return;
      }
      if (row.modelPath) {
        row.wellLabel = row.modelPath
        row.wellLabelId = row.modelPath
        row.checkStatus = '加载中'
        this.lasTableData.splice(index, 1, row)
        return;
      }
      let data = this.lasModelList;
      for (let i = 0, l = data.length; i < l; i++) {
        if (row.fileHead == data[i].value) {
          row.wellLabel = data[i].value
          row.wellLabelId = data[i].key
          break;
        } else if (row.wellLabel == data[i].value) {
          row.wellLabelId = data[i].key
        } else if (i == l - 1) {
          row.checkStatus = '未匹配到模板'
        }
      }
      this.lasTableData.splice(index, 1, row)
    },
    /**
     * 取消选择
     */
    selectWellCancel() {
      this.wellSelectObj.wellBaseId = '';
      this.wellSelectObj.wellLabel = '';
      this.wellSelectObj.dialogWellVisible = false
    },
    /**
     * 条件查询
     */
    querySearch() {
      this.currentPage = 1;
      this.queryTableData();
    },

    /**
     * 查看历史弹窗
     */
    openHistoryDialog() {
      this.queryHistory().then(data => {
        this.tableHistoryData = data.rows;
        this.totalHistory = data.total;
        this.dialogHistoryVisible = true;
      }).catch(e => {
        this.$message.warning("查询历史失败！")
      })
    },
    /**
     * 查看历史弹窗
     */
    closeHistoryDialog() {
      this.dialogHistoryVisible = false
    },
    /**
     * 页面数据条数改变时
     */
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.queryTableData();
    },
    /**
     * 翻页
     */
    handleCurrentChange(val) {
      this.currentPage = val;
      this.queryTableData();
    },
    /**
     * 页面数据条数改变时
     */
    handleSizeHistoryChange(val) {
      this.currentHistoryPage = 1;
      this.pageHistorySize = val;
      this.queryHistory().then(data => {
        this.tableHistoryData = data.rows;
        this.totalHistory = data.total;
      }).catch(e => {
        this.$message.warning("查询历史失败！")
      })
    },
    /**
     * 翻页
     */
    handleCurrentHistoryChange(val) {
      this.currentHistoryPage = val;
      this.queryHistory().then(data => {
        this.tableHistoryData = data.rows;
        this.totalHistory = data.total;
      }).catch(e => {
        this.$message.warning("查询历史失败！")
      })
    },
    //分页多行变少行，点击翻页不刷新问题
    pageClick(e) {
      if (!this.tableData.length) {
        return false;
      }
    },
    /*获取文件大小*/
    getFileSize(size) {
      return size > 1024 * 1024 * 1024
          ? (size / (1024 * 1024 * 1024)).toFixed(2) + ' GB'
          : size > 1024 * 1024
              ? (size / (1024 * 1024)).toFixed(1) + ' MB'
              : size > 1024
                  ? (size / 1024).toFixed(1) + ' KB'
                  : size + ' Byte'
    },
    // /*las文件上传回调*/
    lasFileChange(file, fileList) {
      if (!this.checkFileType(file)) return
      this.upSingleFile(file.raw)
      this.$refs.uploadLas.clearFiles()
    },
    // /*检测上传文件类型*/
    checkFileType(file) {
      let nameReg = new RegExp(('\\.las') + '$', 'i')
      if (!nameReg.test(file.name)) {
        this.$message({
          type: 'warning',
          message: `${file.name}不符合las文件格式！`
        })
        return false
      } else {
        let fileMaxSize = 1024 * 1024 * 500;
        if (file.size > fileMaxSize) {
          this.$message({
            type: 'warning',
            message: `${file.name}大于500M！`
          })
          return false
        } else {
          return true
        }
      }
    },
    // /*单个文件上传*/
    async upSingleFile(file) {
      let loading = Loading.service({
        fullscreen: true,
        text: "查询中，请稍后",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      let _this = this
      let username = _this.userInfo.loginName;
      let fileUuid = uuid();
      let las = new RegExp(('\\.las') + '$', 'i')
      let fileType = "";
      // let emptyFile = false;
      // if (emptyFile) {
      //   this.$message({
      //     type: 'warning',
      //     message: `检测到文件${file.name}为空文件，已取消该文件上传`
      //   })
      //   return
      // }
      if (las.test(file.name)) {
        fileType = 'las'
      }
      file.status = 0;
      _this.upFilesObj[fileUuid] = file
      _this.updateDialog = true
      let form = new FormData();
      form.append('file', file, file.name)
      form.append('fileKey', fileUuid)
      form.append('creater', username)
      form.append('fileType', fileType)
      form.append('fileDataType', fileType)
      axios({
        url: AJAXPathConfig.dataManage.getBasePath() + '/dataLoad/las/' + _this.project.projectId + '/upload',
        method: "post",
        data: form,
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        success: function (resp) {
          _this.upFilesObj[fileUuid].status = 1
          _this.queryTableData()
        },
        error: function (resp) {
          _this.upFilesObj[fileUuid].status = 2
        }
      }).finally(() => {
        loading.close()
      })
    },
    /**
     * 批量加载
     */
    bulkLoading() {
      if (this.loadingList.length > 10) {
        this.$message({
          type: 'warning',
          message: "每次最多批量加载10个文件！"
        })
        return false;
      }
      if (this.loadingList.length) {
        this.loadingList.forEach((item, index, arr) => {if ((!(item.status == 3 || (item.checkStatus !== '符合' && item.checkStatus !== '已配置'))) || !(item.wellLabel == undefined || item.wellLabel == '')) {
            this.upLoadFile(item)
          } else {
            this.$message({
              type: 'warning',
              message: `${item.fileName}不符合加载要求！`
            })
          }
        })
        this.$refs["las"].clearSelection()
      } else {
        this.$message({
          type: 'warning',
          message: "请选择数据！"
        })
      }
    },
    upLoadFile(row, index) {
      let _this = this;
      let data = {};
      let las = new RegExp(('\\.las') + '$', 'i')
      let fileType = "";
      if (las.test(row.fullFileName)) {
        fileType = 'las';
        data.curvePrefix = row.prefix ? row.prefix : ''
      }
      data.fileTypes = fileType // 项目标识
      data.dataLoadId = row.dataLoadId // 数据加载标识
      data.filePath = row.filePath // 文件路径
      data.fullFileName = row.fullFileName // 带扩展全名
      data.wellLabel = row.wellLabel // 井号 上传las文件时 必填
      data.isAutoMatch = row.isAutoMatch // 数据模板是否自动匹配 yes/no
      data.fileName = row.fullFileName.replace(/\.\S+$/, '')
      data.creater = this.userInfo.loginName
      data.wellLabelId = row.wellLabelId
      // creater
      if (row.isAutoMatch == 'yes') { // 自动匹配
        data.modelFilePath = row.templateFilePath // yes templateFilePath
      } else if (row.isAutoMatch == 'no') {
        data.tableName = row.tableInfoCode // no tableInfoCode eg:core_lithology
        data.headers = row.headers // Array
        data.columns = row.columnInfoCode // Array
        data.colTypes = row.colTypes // Array columnInfoType
        data.isUniques = row.isUnique // Array isUnique唯一标识符
        data.colPatterns = row.colPatterns // Array colPatterns时间格式标识符
      }
      axios({
        url: AJAXPathConfig.dataManage.getBasePath() + '/dataLoad/las/' + _this.project.projectId + '/data_load',
        method: "post",
        data: data,
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        success: (resp) => {
          // let itemIndex = this.lasTableData.findIndex(function (val, index, arr) {
          //   return val.dataLoadId == row.dataLoadId
          // })
          this.$message({type: 'success', message: "加载中"})
          this.queryTableData()
          // this.lasTableData.splice(itemIndex, 1)
        },
        error: (resp) => {
          // let itemIndex = this.lasTableData.findIndex(function (val, index, arr) {
          //   return val.dataLoadId == row.dataLoadId
          // })
          this.$message({
            type: 'warning',
            message: resp
          })
          row.status = 2
        }
      })
    },
    /*删除las记录*/
    deleteClick(row, index, historyKey) {
      let _this = this;
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        axios({
          url: AJAXPathConfig.dataManage.getBasePath() + '/dataLoad/las/delete/' + row.dataLoadId,
          method: "delete",
          success: function (resp) {
            _this.$message({
              type: "success",
              message: "删除成功!"
            });
            _this.queryTableData()
          },
          error: function (resp) {
            _this.$message({
              type: "error",
              message: "删除记录失败!"
            });
            _this.queryTableData()
          }
        })
      }).catch(() => {
        _this.$message({
          type: "info",
          message: "已取消删除"
        });
      });
    },
    /*文件夹上传触发事件*/
    filesDirectoryEvent() {
      document.getElementById('uploadDirectory').click()
    },
    /**
     * 文件夹上传绑定事件
     */
    bindUpdateHandle(event) {
      let files = event.target.files;
      if (!files.length) {
        this.$message({
          type: 'warning',
          message: "此文件夹为空！"
        })
        return
      } else if (files.length > this.uploadLimit) {
        this.$message({
          type: 'warning',
          message: `每次上传文件数量不超过${this.uploadLimit}个！`
        })
        return
      }
      for (let i = 0, l = files.length; i < l; i++) {
        if (!this.checkFileType(files[i])) continue
        this.upSingleFile(files[i])
        if (i == files.length - 1) {
          document.getElementById('uploadDirectory').value = ''
        }
      }
    },
    /*文件列表选中事件*/
    uploadFileSelection(val) {
      this.loadingList = val
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "数据导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.queryTableData()
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    checkFileExist(){
      return new Promise((resolve,reject)=>{
        this.$nextTick(()=>{
          this.upload.url = process.env.VUE_APP_BASE_API + "/assessDataMessage/dataManage/dataLoad/uploadingFile" +
            "?projectId="+this.project.projectId +
            "&typeId="+this.fileType.id +
            //"&file="+file.raw +
            "&typeName="+this.fileType.code +
            "&parentType="+this.fileType.pid +
            //"&userCode="+ this.userInfo.loginName +
            "&stepId="+this.project.stepId +
            "&nodeId="+this.project.nodeList.map(n => n.id).join(",");
          resolve();
        })
      });
    },
  },

}
;
</script>
<style scoped>
* >>> .el-dialog__body {
  padding: 0 20px;
}

.leftTree >>> .is-current .el-tree-node__content {
  background-color: #deeaf7;
}

.leftTree >>> .is-current .el-tree-node__children .el-tree-node__content {
  background-color: #ffffff;
}

.dialogForForm >>> .el-dialog__body {
  padding: 0 10px 10px;
}

.wisWellDialog.dialogForForm >>> .el-dialog {
  min-width: 300px;
  width: 30vw;
}

::v-deep .el-upload {
    display: inline;
    text-align: center;
    cursor: pointer;
    outline: 0;
}

::v-deep.upload-demo {
    display: inline-block;
}

::v-deep .el-card__body, .el-main {
    padding: 15px 20px;
}

</style>
